package org.zzh.springboot.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.zzh.springboot.entity.User;
import org.zzh.springboot.service.UserService;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {
    //去登录页面
//    @GetMapping("/toLogin")
//    public String toLogin(){
//        return "index";
//    }
    @Autowired
    private UserService userService;
    //登录功能
//    @PostMapping("/doLogin")
//    public String login(
//            @RequestParam(value = "name") String name,
//            @RequestParam(value = "password") String password
//            , Map<String, Object> maps, HttpSession session) {
//        User user = userService.login(name, password);
//        if (user != null) { //将用户信息保存到session中去用户列表页面
//            session.setAttribute("user", user);
//            return "redirect:/main";//重定向到/main请求-防止表单重复提交
//        } else { //去登录页面
//            maps.put("msg", "用户名或密码不正确!");
//            return "login";
//        }
//    }
    @PostMapping("/doLogin")
    public String login(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "password") String password,
            @RequestParam(value = "code") String inputCode, // 获取用户输入的验证码
            Map<String, Object> maps,
            HttpSession session) {

        // 验证码校验
        String sessionCode = (String) session.getAttribute("code");
        if (sessionCode == null || !sessionCode.equalsIgnoreCase(inputCode)) {
            maps.put("msg", "验证码错误!");
            return "login";
        }

        // 清除已使用的验证码
        session.removeAttribute("code");

        User user = userService.login(name, password);
        if (user != null) {
            session.setAttribute("user", user);
            return "redirect:/main";
        } else {
            maps.put("msg", "用户名或密码不正确!");
            return "login";
        }
    }
    //查询所有用户
//    @GetMapping("/getUserList")
//    public String getList(Model model){
//        List<User> userList=userService.getUserList();
//        if(userList!=null){
//            model.addAttribute("userList",userList);
//            return "ulist";
//        }else{
//            return null;
//        }
//
//    }
    //查询单个用户
    @GetMapping("/getUserById/{id}")
    public String selectUserById(@PathVariable("id") Integer id, Model model){
        User user = userService.selectUserById(id);
        if(user!=null){
            model.addAttribute("user",user);
            return "detail";
        }else {
            return null;
        }
    }
    //删除用户信息
    @RequestMapping("/deleteUserById/{id}")
    public String deleteUserById(@PathVariable("id") Integer id, Model model){
        int num = userService.deleteUserById(id);
        if(num>0){
            model.addAttribute("msg","delete success!");

        }else {
            model.addAttribute("msg","delete fail!");

        }
        return "forward:/getUserList";

    }

    //去修改用户页面
    @GetMapping("/updateUserById/{id}")
    public String updateUserById(@PathVariable("id") Integer id, Model model){
        User user = userService.selectUserById(id);
        if(user!=null){
            model.addAttribute("user",user);
            return "update";
        }else {
            return null;
        }
    }
    //修改用户页面
    @RequestMapping ("/updateUser")
    public String updateUser(User user){
        int num = userService.updateUser(user);
        if(num>0){
            return "redirect:/getUserList";
        }else {
            return null;
        }
    }
    //增加用户页面
    @PostMapping("/addUser")
    public String addUser(User user){
        int num = userService.addUser(user);
        if(num>0){
            return "redirect:/getUserList";
        }else {
            return null;
        }
    }

    //退出登录功能
    @RequestMapping("quitUser")
    public String quitUser(){
        return "redirect:/toLogin";
    }
    //实现分页功能
    @GetMapping("/getUserList")
    public String getList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize,
            Model model) {

        List<User> userList = userService.getUserList(pageNum, pageSize);
        PageInfo<User> pageInfo = new PageInfo<>(userList);

        model.addAttribute("userList", userList);
        model.addAttribute("pageInfo", pageInfo); // 传递分页信息到前端
        return "ulist";
    }
    // 根据用户名模糊查询
//    @GetMapping("/searchUsers")
//    public String searchUsers(
//            @RequestParam(value = "keyword", required = false) String keyword,
//            @RequestParam(defaultValue = "1") Integer pageNum,
//            @RequestParam(defaultValue = "5") Integer pageSize,
//            Model model) {
//
//        List<User> userList = userService.searchUsers(keyword, pageNum, pageSize);
//        PageInfo<User> pageInfo = new PageInfo<>(userList);
//
//        model.addAttribute("userList", userList);
//        model.addAttribute("pageInfo", pageInfo);
//        model.addAttribute("keyword", keyword); // 回显搜索关键词
//        return "ulist";
//    }
    // 增添全部删除功能
    @PostMapping("/deleteAllByUsername")
    public String deleteAllByUsername(
            @RequestParam(value = "name", required = false) String name,
            HttpSession session,
            Model model) {

        int deletedCount = userService.deleteAllByUsername(name);
        session.setAttribute("msg", "成功删除 " + deletedCount + " 条记录");
        return "redirect:/getUserList"; // 删除后跳回列表页
    }

    // 跳转到注册页面
    @GetMapping("/toRegister")
    public String toRegister() {
        return "register";
    }

    // 处理注册请求
    @PostMapping("/doRegister")
    public String register(User user,Model model) {

        // 检查用户名是否已存在
        if (userService.findUserByName(user.getName()) != null) {
            model.addAttribute("msg", "用户名已存在！");
            return "register";
        }
        int result = userService.addUser(user);
        if (result > 0) {
            return "redirect:/toLogin"; // 注册成功跳转到登录页
        } else {
            model.addAttribute("msg", "注册失败，请重试！");
            return "register";
        }
    }
    //多条件查询
    @GetMapping("/searchUsers")
    public String searchUsers(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "sex", required = false) String sex,
            @RequestParam(value = "address", required = false) String address,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize,
            Model model) {

        List<User> userList = userService.searchUsers(name, sex, address, pageNum, pageSize);
        PageInfo<User> pageInfo = new PageInfo<>(userList);

        model.addAttribute("userList", userList);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("name", name);    // 回显姓名条件
        model.addAttribute("sex", sex);      // 回显性别条件
        model.addAttribute("address", address); // 回显地址条件
        return "ulist";
    }
    //    登陆验证
    @GetMapping("/captcha")
    public void generateCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        // 生成线条干扰验证码（宽200px，高100px，4位字符，10条干扰线）
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 10);
        String code = lineCaptcha.getCode(); // 获取验证码文本
        session.setAttribute("code",code);
        // 设置验证码5分钟有效
        session.setMaxInactiveInterval(300);
        lineCaptcha.write(response.getOutputStream()); // 输出到响应流
        response.getOutputStream().close(); // 关闭流防止资源泄漏
    }

}